<?php
namespace app\index\controller;
use think\Session;
use think\Controller;
use think\Exception;
use app\index\model\base;
use app\index\model\published_seismic_database;
use app\index\controller\Util;

class pubear extends Controller 
{
  public function baseInfo() {
    //网站截图目录初试化 start
    date_default_timezone_set('PRC');
    $street=$_POST['street']; //街道名称
    $district=$_POST['district'];//县名称
    $EQTTIME=$_POST['time'];//发震时间
    $LONGTITUDE=$_POST['longtitude'];//经度
    $LATITUDE=$_POST['latitude'];//纬度
    $MAGNITUDE=$_POST['magnitude'];//震级
    $DEPTH=$_POST['depth'];//震源深度
    $CITY=$_POST['city'];//城市名称
    $RANGE='100';
    $province=$_POST['province'];//省名称
    $Intensity=$_POST['Intensity'];
    $util = new Util();
    $util->sendEarthInfo($LONGTITUDE, $LATITUDE, $MAGNITUDE, $DEPTH, $EQTTIME);
    return $this->pubEQ($street,$district,$EQTTIME,$LONGTITUDE,$LATITUDE,$MAGNITUDE,$DEPTH,$CITY,$RANGE,$province,$Intensity);
  }

  public function pubEQ($street,$district,$EQTTIME,$LONGTITUDE,$LATITUDE,$MAGNITUDE,$DEPTH,$CITY,$RANGE,$province,$Intensity) {
    $pythonres = $this->req_python($LONGTITUDE, $LATITUDE);
    $pyGetName='';
    $base = new base();
    $results=$base->baseInfo($district,$CITY,$province,$street,$pyGetName);
    //坤 修改的部分
    // 判断是否传入县名
    // 判断一下最近的那个地区
    $Mindistance=999999;$i=0;$flag=0;
    foreach ($results as $value) {
        $d=sqrt(pow($value['longtitude']-$LONGTITUDE,2)+pow($value['latitude']-$LATITUDE,2));
        if($Mindistance>$d){
            $Mindistance=$d;
            $flag=$i;
        }
        $i++;
    }
    $ischeck = 0;
    $pubEar = new published_seismic_database();
    
    if($results) {
      //$pubEar->updateEqtInfo();
      $OBJECTID = $results[$flag]['OBJECTID'];
      $x_longtitude = $results[$flag]['longtitude'];
      $x_latitude = $results[$flag]['latitude'];
      $GB_CODE = $results[$flag]['GB_CODE'];
      $name = $results[$flag]['name'];
      $abbreviation = $results[$flag]['abbreviation'];
      $city = $results[$flag]['city'];
      $province = $results[$flag]['province'];
      $tel = $results[$flag]['tel'];
      $remark = $results[$flag]['remark'];
      $abvProvince = $results[$flag]['abvProvince'];
      $fullName = $results[$flag]['fullName'];
      $abbreviationThree = $results[$flag]['abbreviationThree'];
      $POP_ALL = $results[$flag]['POP_ALL'];
      $POP_COUNTRYSIDE = $results[$flag]['POP_COUNTRYSIDE'];
      $POP_TOWN = $results[$flag]['POP_TOWN'];
      $GDP = $results[$flag]['GDP'];
      $FST_INDUSTRY = $results[$flag]['FST_INDUSTRY'];
      $SND_INDUSTRY = $results[$flag]['SND_INDUSTRY'];
      $TRD_INDUSTRY = $results[$flag]['TRD_INDUSTRY'];
      $townNum = $results[$flag]['townNum'];
      $villageNum = $results[$flag]['villageNum'];
      $climate = $results[$flag]['climate'];
      $area = $results[$flag]['area'];
      if($pythonres&&$pythonres['min']) {
          $altitudeL = floor($pythonres['min']);
          $altitudeAverage = floor($pythonres['mean']);
          $altitudeH = floor($pythonres['max']);
      } else {
          $altitudeL = floor($results[$flag]['altitudeL']);
          $altitudeH =floor( $results[$flag]['altitudeH']);
          $altitudeAverage = floor($results[$flag]['altitudeAverage']);
      }
      $altitudeLName = $results[$flag]['altitudeLName'];
      $altitudeHName = $results[$flag]['altitudeHName'];
      $topographic = $results[$flag]['topographic'];
      $villageAverIncom = $results[$flag]['villageAverIncom'];
      $urbanAverIncome = $results[$flag]['urbanAverIncome'];
      $Population = $results[$flag]['Population'];
      $Economics = $results[$flag]['Economics'];

      //苏苏改动
      $ID = md5(time() . mt_rand(1,1000000));
      $params = array(
        'ID' => $ID,
        'EQTTIME' => $EQTTIME,
        'LONGITUDE' => $LONGTITUDE,
        'LATITUDE' => $LATITUDE,
        'MAGNITUDE' => $MAGNITUDE,
        'DEPTH' => $DEPTH,
        'Intensity' => $Intensity,
        'EQTRANGE' => $RANGE,
        'OBJECTID' => $OBJECTID,
        'x_longitude' => $x_longtitude,
        'x_latitude' => $x_latitude,
        'GB_CODE' => $GB_CODE,
        'eqtname' => $name,
        'abbreviation' => $abbreviation,
        'city' => $city,
        'province' => $province,
        'tel' => $tel,
        'remark' => $remark,
        'abvProvince' => $abvProvince,
        'fullName' => $fullName,
        'abbreviationThree' => $abbreviationThree,
        'POP_ALL' => $POP_ALL,
        'POP_COUNTRYSIDE' => $POP_COUNTRYSIDE,
        'POP_TOWN' => $POP_TOWN,
        'GDP' => $GDP,
        'FST_INDUSTRY' => $FST_INDUSTRY,
        'SND_INDUSTRY' => $SND_INDUSTRY,
        'TRD_INDUSTRY' => $TRD_INDUSTRY,
        'townNum' => $townNum,
        'villageNum' => $villageNum,
        'climate' => $climate,
        'area' => $area,
        'altitudeL' => $altitudeL,
        'altitudeLName' => $altitudeLName,
        'altitudeH' => $altitudeH,
        'altitudeHName' => $altitudeHName,
        'altitudeAverage' => $altitudeAverage,
        'topographic' => $topographic,
        'villageAverIncom' => $villageAverIncom,
        'urbanAverIncome' => $urbanAverIncome,
        'Population' => $Population,
        'Economics' => $Economics
      );
      $insertid = $pubEar->eqtinferInfo($params);
      if($insertid) {
        Session::set('equnique',$ID);
        $ischeck = 1;
      }
    }

    if($ischeck) {
      $info = "地震发布成功，等待推送！";
      $util = new Util();
      $util->sendLogInfo($info);
    } else {
      $info = "地震发布失败！";
      $util = new Util();
      $util->sendLogInfo($info);
    }
    return $ischeck;
  }

  public function req_python ($lng, $lat) {
      $url="http://10.5.160.121/api/data/get_district_elevation/";
      $result = $this->get($url, array('longitude' => $lng, 'latitude' => $lat,'format'=>'json'));
      return json_decode($result,true);
  }

  public function get( $url, $params=array()) {
      $opts = array(
          'http'=>array(
              'method'=>"GET"
          )
      );
      $url .= empty($params)?"":"?".http_build_query($params);
      $context = stream_context_create($opts);
              try{
          $result =  file_get_contents($url,false,$context);    
      }catch(Exception $e){
          $result = '';
      }
      return $result;
  }

  public function returnHistEart() {
      $lon=$_SESSION['longtitude'];
      $lat=$_SESSION['latitude'];
      $dis=1;
      $results=$this->PubEarthquake_Model->searchEartquake($lat,$lon,$dis);
      echo json_encode($results,JSON_UNESCAPED_UNICODE);

  }

  public function OPenSocket(){
      $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
      $connection = socket_connect($socket, '10.5.160.121', 7080);
      echo  "Client send success \n";
      $this->login($socket);
      while ($out = socket_read($socket, 8,PHP_BINARY_READ)) {
          $response=$this->handleRespon($socket,$out);
          $Mode = $response->Head->Mode;
          if($Mode=="Response"){
            if($response->Body->StatusCode==200){
              echo "****************login sucess****************\n";
              echo "****************start subScribe****************\n";
              $this->subScribe($socket);
            }
          }else if($Mode=="SubscribeResponse"){
            if($response->Body->StatusCode==200){
              echo "****************subScribe sucess****************\n";
              
            }
          }else if($Mode=="Publish"){
            if($response->Body->Node=="earthquake.trigger"){
              $Parameters = $response->Body->Parameters;

              $EQTTIME=$Parameters->earthquake_time;//发震时间
              $LONGTITUDE=$Parameters->longitude;//经度
              $MAGNITUDE=$Parameters->magnitude;//震级
              $LATITUDE=$Parameters->latitude;//纬度
              $DEPTH=$Parameters->depth;//震源深度
              $Intensity=$DEPTH+2;
              $RANGE='100';
              $url='https://maps.google.cn/maps/api/geocode/json?latlng='.$LATITUDE.','.$LONGTITUDE.'&key=AIzaSyCbLfKHIBp1w36w3y04cK92v2uYNUuO9OU';
              $ch = curl_init();
              $timeout = 5;
              curl_setopt($ch, CURLOPT_URL, $url);
              curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
              curl_setopt($ch,CURLOPT_ENCODING ,'gzip');
              curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //跳过ssl认证；
              $file_contents = curl_exec($ch);
              curl_close($ch);
              if($file_contents->status=='OK'){
                  $res = $file_contents ->results[0];
                  $street=$res->address_components[0]->long_name;
                  $district = $res ->address_components[1]->long_name;
                  $CITY = $res ->address_components[2]->long_name;
                  $province = $res ->address_components[3] ->long_name;
                  $this->pubEQ($street,$district,$EQTTIME,$LONGTITUDE,$LATITUDE,$MAGNITUDE,$DEPTH,$CITY,$RANGE,$province,$Intensity);
                  
              }else{
                  echo 'googel key 过期';
              }
              echo '接收到地震推送';
            }
            
          
        }else{
          echo "get data file";
        }
  
      }    
  }

  private function handleRespon($socket,$out){
      $response = null;
      $out=unpack('J',$out);
        if($out[1]==97114859022255){
          $out = socket_read($socket,4,PHP_BINARY_READ);
          $out = unpack('N',$out);
          $out = socket_read($socket,$out[1],PHP_BINARY_READ);
          $response =  json_decode ($out);
          
      }
      return $response;
  }

  private function login($socket){
      $send_data = json_encode(["Head"=>["TransactionId"=>1,"Mode"=>"Request"],"Body"=>[   "RequestId"=>100,"Method"=>"developer.login","Parameters"=>["app_id"=>"ss61d15fb2","app_key"=>"61d1623251d411e88c410cda411dcf6a"]]]);
      $len = strlen($send_data);
      $head =$this->getHead($len);
      socket_write($socket,$head.$send_data,12+$len);
  }

  private function getHead($len)
  {
    $aa =0X585350ACA7AF;
    $pack= pack('J',$aa);
    $num=pack('N',$len);
    return $pack.$num;
    # code...
  }

  private function subScribe($socket)
  {
    $data=array(
              "Head"=>array(
                "TransactionId"=>2,
                "Mode"=>"Subscribe"
              ),
              "Body"=>array(
                "Node"=>"earthquake.trigger"
              )
    );
    $dataJ=json_encode($data);
    $len=strlen($dataJ);
    $head=$this->getHead($len);
    socket_write($socket,$head.$dataJ,12+$len);
  }
}
